package com.wswy.wyjk.ui.splash;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;

import com.kaijia.adsdk.Tools.KjSplashAd;
import com.kaijia.adsdk.center.AdCenter;
import com.my.httpapi.api.annotation.ViewL;
import com.my.httpapi.api.baseMyView.IosAlertDialog;
import com.my.httpapi.api.baseUtils.Toast;
import com.my.httpapi.api.baseView.BaseActivity;
import com.qq.e.ads.splash.SplashAD;
import com.qq.e.ads.splash.SplashADListener;
import com.qq.e.comm.managers.GDTADManager;
import com.qq.e.comm.util.AdError;

import com.tencent.mmkv.MMKV;
import com.wswy.wyjk.R;
import com.wswy.wyjk.api.Api;
import com.wswy.wyjk.api.Constant;
import com.wswy.wyjk.api.MMKVConstant;
import com.wswy.wyjk.api.OldApi;
import com.wswy.wyjk.api.entity.AdverConfigEntity;
import com.wswy.wyjk.api.entity.AdverItemConfigEntity;
import com.wswy.wyjk.api.entity.DeviceMod;
import com.wswy.wyjk.api.entity.RequestParameter;
import com.wswy.wyjk.core.App;
import com.wswy.wyjk.ui.main.MainActivity;
import com.wswy.wyjk.ui.main.WebViewActivity;
import com.wswy.wyjk.ui.main.choose.PracticeTypeActivity;
import com.wswy.wyjk.utils.AdverConfigUtil;

import java.util.List;

import static com.tencent.bugly.Bugly.applicationContext;

@ViewL(R.layout.activity_splash)
public class SplashActivity extends BaseActivity implements SplashADListener, SplashController.MyKjSplashAdListener {
    private SplashAD splashAD;
    private ViewGroup container;
    private TextView skipView;
    private static final String SKIP_TEXT = "跳过 %d";

    public boolean canJump = false;

    private String postId;

    /**
     * 为防止无广告时造成视觉上类似于"闪退"的情况，设定无广告时页面跳转根据需要延迟一定时间，demo
     * 给出的延时逻辑是从拉取广告开始算开屏最少持续多久，仅供参考，开发者可自定义延时逻辑，如果开发者采用demo
     * 中给出的延时逻辑，也建议开发者考虑自定义minSplashTimeWhenNoAD的值（单位ms）
     **/
    private int minSplashTimeWhenNoAD = 2000;
    /**
     * 记录拉取广告的时间
     */
    private long fetchSplashADTime = 0;
    private Handler handler = new Handler(Looper.getMainLooper());

    //铠甲联盟
    private AdCenter adCenter;

    private SplashController splashController;

    private TextView tv_adv_tip;
    @Override
    protected void initData(Bundle savedInstanceState) {
        initView();
        initData();
        initKaijialianmeng();
        showDialog();
    }

    @Override
    protected String showTitle() {
        return null;
    }

    @Override
    protected boolean statusBarIsBlack() {
        return false;
    }

    @Override
    protected void destroy() {
        handler.removeCallbacksAndMessages(null);
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        canJump = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        adCenter.onResume();
        if (canJump) {
            next();
        }
        canJump = true;
    }

    /**
     * 开屏页一定要禁止用户对返回按钮的控制，否则将可能导致用户手动退出了App而广告无法正常曝光和计费
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initView() {
        container = findViewById(R.id.splash_container);
        skipView = findViewById(R.id.skip_view);
        tv_adv_tip=findViewById(R.id.tv_adv_tip);
    }

    private void initData() {
        splashController = new SplashController(getApplicationContext(), this);
        //开启定时器，如果广告10s内没有结束或者没有反应直接进入下个页面
        timer.start();
    }

    private void initKaijialianmeng() {
        adCenter = AdCenter.getInstance(this);
        adCenter.onCreate();
    }

    private void DelayGotoNextPage() {
        //当没有广告的时候延迟2s跳转
        handler.postDelayed(() -> gotoNextPage(), 2 * 1000);
    }

    private void gotoNextPage() {
        if (App.INSTANCE.getPracticeContext() != null) {
            intentFinish(MainActivity.class);
        } else {
            intentFinish(PracticeTypeActivity.class);
        }
    }

    @Override
    public void onADDismissed() {
        next();
    }

    @Override
    public void onNoAD(AdError adError) {
        /**
         * 为防止无广告时造成视觉上类似于"闪退"的情况，设定无广告时页面跳转根据需要延迟一定时间，demo
         * 给出的延时逻辑是从拉取广告开始算开屏最少持续多久，仅供参考，开发者可自定义延时逻辑，如果开发者采用demo
         * 中给出的延时逻辑，也建议开发者考虑自定义minSplashTimeWhenNoAD的值
         **/
        long alreadyDelayMills = System.currentTimeMillis() - fetchSplashADTime;//从拉广告开始到onNoAD已经消耗了多少时间
        long shouldDelayMills = alreadyDelayMills > minSplashTimeWhenNoAD ? 0 : minSplashTimeWhenNoAD
                - alreadyDelayMills;//为防止加载广告失败后立刻跳离开屏可能造成的视觉上类似于"闪退"的情况，根据设置的minSplashTimeWhenNoAD
        // 计算出还需要延时多久
        handler.postDelayed(() -> gotoNextPage(), shouldDelayMills);
    }

    @Override
    public void onADPresent() {
        container.setVisibility(View.VISIBLE);
        container.setBackgroundColor(Color.WHITE);
        tv_adv_tip.setVisibility(View.VISIBLE);
    }

    @Override
    public void onADClicked() {
    }

    @Override
    public void onADTick(long millisUntilFinished) {
        skipView.setBackgroundResource(R.drawable.btn_skip);
        if (skipView != null) {
            skipView.setText(String.format(SKIP_TEXT, (Math.round(millisUntilFinished / 1000f) + 1)));
        }
    }

    @Override
    public void onADExposure() {

    }

    @Override
    public void onADLoaded(long l) {

    }

    /**
     * 拉取开屏广告，开屏广告的构造方法有3种，详细说明请参考开发者文档。
     *
     * @param activity      展示广告的activity
     * @param adContainer   展示广告的大容器
     * @param skipContainer 自定义的跳过按钮：传入该view给SDK后，SDK会自动给它绑定点击跳过事件。SkipView的样式可以由开发者自由定制，其尺寸限制请参考activity_splash.xml或者接入文档中的说明。
     * @param posId         广告位ID
     * @param adListener    广告状态监听器
     * @param fetchDelay    拉取广告的超时时长：取值范围[3000, 5000]，设为0表示使用广点通SDK默认的超时时长。
     */
    private void fetchSplashAD(Activity activity, ViewGroup adContainer, View skipContainer, String posId, SplashADListener adListener, int fetchDelay) {
        fetchSplashADTime = System.currentTimeMillis();
        splashAD = new SplashAD(activity, skipContainer, posId, adListener, fetchDelay);
        splashAD.fetchAndShowIn(adContainer);
    }

    @SuppressLint("CheckResult")
    private void checkAndRequestPermission() {
        if (Build.VERSION.SDK_INT < 23) {
            fetchSplashAD(this, container, skipView, postId, this, 0);
            return;
        }
        //获取权限，权限获取失败也继续
//        RxPermissions rxPermissions = new RxPermissions(this);
//        rxPermissions.request(
//                Manifest.permission.ACCESS_FINE_LOCATION,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                .subscribe(aBoolean -> {
//                    fetchSplashAD(this, container, skipView, postId, this, 0);
//                });
        fetchSplashAD(this, container, skipView, postId, this, 0);
    }

    /**
     * 设置一个变量来控制当前开屏页面是否可以跳转，当开屏广告为普链类广告时，点击会打开一个广告落地页，此时开发者还不能打开自己的App主页。当从广告落地页返回以后，
     * 才可以跳转到开发者自己的App主页；当开屏广告是App类广告时只会下载App。
     */
    private void next() {
        if (canJump) {
            gotoNextPage();
        } else {
            canJump = true;
        }
    }

    private void requestAdv() {
        subscribe(OldApi.getApi().getAdvertConfig(RequestParameter.generate().getSingedParams()),
                request(data -> getData((AdverConfigEntity) data), err -> gotoNextPage(), false));
    }

    private void getData(AdverConfigEntity splashEntity) {
        //首页广告
        List<AdverItemConfigEntity> bannerList = splashEntity.getHomeBanner();
        if(bannerList == null || bannerList.size() == 0 ){
            AdverConfigUtil.isShowBanner = false;
            AdverConfigUtil.isShowBannerAD=false;
        }else {
            for (int i = 0; i < bannerList.size(); i++) {
                if (bannerList.get(i).getType().equals("custom") && bannerList.get(i).getWeight() == 0) {
                    AdverConfigUtil.isShowBanner = false;
                } else if (bannerList.get(i).getType().equals("custom") && bannerList.get(i).getWeight() == 100) {
                    AdverConfigUtil.homeBannerUrl = bannerList.get(0).getImageUrl();
                    AdverConfigUtil.homeBannerLinkUrl = bannerList.get(0).getLinkUrl();
                } else if (bannerList.get(i).getType().equals("gdt") && bannerList.get(i).getWeight() == 0) {
                    AdverConfigUtil.isShowBannerAD = false;
                } else if (bannerList.get(i).getType().equals("gdt") && bannerList.get(i).getWeight() == 100) {
                    AdverConfigUtil.bannerADPOSTID = bannerList.get(i).getBannerId();
                }
            }
        }
        //试题页面广告
        List<AdverItemConfigEntity> questionPageList = splashEntity.getQuestionPage();
        if(questionPageList == null || questionPageList.size() == 0 ){
            AdverConfigUtil.isShowQuestionAD=false;
        }else {
            for (int i = 0; i < questionPageList.size(); i++) {
                if (questionPageList.get(i).getType().equals("gdt") && questionPageList.get(i).getWeight() == 0) {
                    AdverConfigUtil.isShowQuestionAD = false;
                } else if (questionPageList.get(i).getType().equals("gdt") && questionPageList.get(i).getWeight() == 100) {
                    AdverConfigUtil.questionADPOSTID = questionPageList.get(i).getBannerId();
                }
            }
        }

        //开屏广告
        List<AdverItemConfigEntity> list = splashEntity.getOpenScreen();
        if (list == null || list.size() == 0) {
            DelayGotoNextPage();
            return;
        }
        int position = 0;
        for (int i = 0; i < list.size(); i++) {
            //广点通
            if (list.get(i).getType().equals("gdt")) {
                if (list.get(i).getWeight() == 100) {
                    GDTADManager.getInstance().initWith(this, list.get(i).getAppId());
                    postId = list.get(i).getBannerId();
                    checkAndRequestPermission();
                    return;
                } else {
                    position++;
                }
            }
            //铠甲联盟
            if (list.get(i).getType().equals("kaijia")) {
                if (list.get(i).getWeight() == 100) {
                    adCenter.setAppID(this, list.get(i).getAppId());
                    new KjSplashAd(this, list.get(i).getBannerId(), container, splashController.splashADLinstener); //请求广告
                    return;
                } else {
                    position++;
                }
            }
        }
        if (position == list.size()) {
            DelayGotoNextPage();
            return;
        }
    }

    public void requestDevice() {
        subscribe(Api.getApi().requestDevice(RequestParameter.generate().addAll(splashController.getDeviceInfoMap()).getUUIDParams()),
                request(data -> getUUID((DeviceMod) data), false));
    }

    private void getUUID(DeviceMod deviceMod) {
        if (deviceMod != null && !TextUtils.isEmpty(deviceMod.uuid)) {
            SPUtils.getInstance().put(Constant.SP_UUID_KEY, deviceMod.uuid);
            subscribe(OldApi.getApi().getAdvertConfig(RequestParameter.generate().getSingedParams()),
                    request(data -> getData((AdverConfigEntity) data), err -> gotoNextPage(), false));
        }
    }

    @Override
    public void onAdDismiss() {
        gotoNextPage();
    }

    @Override
    public void onAdShow() {
        tv_adv_tip.setVisibility(View.VISIBLE);
    }

    private void showAD() {
        //先判断有没有uuid
        if (SPUtils.getInstance().contains(Constant.SP_UUID_KEY)) {
            requestAdv();
        } else {
            requestDevice();
        }
    }

    private void showDialog() {
        MMKV kv = MMKV.defaultMMKV();
        boolean bValue = kv.decodeBool(MMKVConstant.PRIVACYAGREEMENT);
        if (bValue) {
            showAD();
            return;
        }
        SpannableStringBuilder sb = new SpannableStringBuilder();
        SpannableString content = new SpannableString(getResources().getString(R.string.dialog_content));
        content.setSpan(new ForegroundColorSpan(
                        ContextCompat.getColor(
                                this,
                                R.color.textColorPrimary_70
                        )
                ), 0, content.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE
        );
        sb.append(content);
        SpannableString service1 = new SpannableString("《用户服务协议》");
        service1.setSpan(
                new ForegroundColorSpan(ContextCompat.getColor(this, R.color.colorPrimary)),
                0,
                service1.length(),
                SpannableString.SPAN_INCLUSIVE_EXCLUSIVE
        );
        service1.setSpan(new ClickableSpan() {

            @Override
            public void onClick(@NonNull View view) {
                Intent intent = new Intent(SplashActivity.this, WebViewActivity.class);
                intent.putExtra("type", "用户协议");
                startActivity(intent);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
                ds.setColor(ContextCompat.getColor(applicationContext, R.color.colorPrimary));
                ds.clearShadowLayer();
            }
        }, 0, service1.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        sb.append(service1);
        content = new SpannableString("及");
        content.setSpan(
                new ForegroundColorSpan(
                        ContextCompat.getColor(
                                this,
                                R.color.textColorPrimary_70
                        )
                ), 0, content.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE
        );
        sb.append(content);
        SpannableString service = new SpannableString("《隐私政策》");
        service.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.colorPrimary)),
                0,
                service.length(),
                SpannableString.SPAN_INCLUSIVE_EXCLUSIVE
        );
        service.setSpan(new ClickableSpan() {

            @Override
            public void onClick(@NonNull View view) {
                Intent intent = new Intent(SplashActivity.this, WebViewActivity.class);
                intent.putExtra("type", "隐私政策");
                startActivity(intent);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
                ds.setColor(ContextCompat.getColor(applicationContext, R.color.colorPrimary));
                ds.clearShadowLayer();
            }
        }, 0, service.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        sb.append(service);
        content = new SpannableString("。并确认您已了解我们对您个人信息的处理方式。\n");
        content.setSpan(new ForegroundColorSpan(
                        ContextCompat.getColor(
                                this,
                                R.color.textColorPrimary_70
                        )
                ), 0, content.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE
        );
        sb.append(content);
        SpannableString hint = new SpannableString("点击『同意』，开始使用本产品，我们将尽力保护您的隐私信息。");
        hint.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.textColorPrimary_40)),
                0,
                hint.length(),
                SpannableString.SPAN_INCLUSIVE_EXCLUSIVE
        );
        sb.append(hint);
        IosAlertDialog dialog = new IosAlertDialog(this).builder().setTitle("用户隐私协议说明").setMsg(sb)
                .setNegativeButton("不同意", view -> finish()).setPositiveButton("同意", view -> {
                    kv.encode(MMKVConstant.PRIVACYAGREEMENT, true);
                    showAD();
                });
        dialog.show();
    }

    private CountDownTimer timer = new CountDownTimer(10 * 1000, 1000) {
        public void onTick(long millisUntilFinished) {

        }

        public void onFinish() {
            gotoNextPage();
        }
    };
}
